package com.arvin.faceDetect.utils

import android.util.Log
import android.util.LruCache
import com.google.mlkit.vision.face.Face

object FeatureCache {
    private const val TAG = "FeatureCache"
    private const val MAX_CACHE_SIZE = 100  // 最多缓存100个特征
    private const val CACHE_TIMEOUT = 5000L  // 缓存5秒

    private val cache = object : LruCache<String, CachedFeature>(MAX_CACHE_SIZE) {
        override fun entryRemoved(
            evicted: Boolean,
            key: String,
            oldValue: CachedFeature,
            newValue: CachedFeature?
        ) {
            if (evicted) {
                Log.d(TAG, "特征缓存被移除: $key")
            }
        }

        override fun sizeOf(key: String, value: CachedFeature): Int {
            return 1
        }
    }

    /**
     * 获取缓存的特征
     */
    fun get(key: String): FloatArray? {
        val cached = cache.get(key)
        return if (cached != null && !isExpired(cached.timestamp)) {
            Log.d(TAG, "命中特征缓存: $key")
            cached.features
        } else {
            Log.d(TAG, "特征缓存未命中或已过期: $key")
            null
        }
    }

    /**
     * 存入特征缓存
     */
    fun put(key: String, features: FloatArray) {
        cache.put(key, CachedFeature(features, System.currentTimeMillis()))
        Log.d(TAG, "存入特征缓存: $key")
    }

    /**
     * 生成缓存键
     */
    fun generateKey(face: Face, timestamp: Long): String {
        return "${face.trackingId}_${timestamp / CACHE_TIMEOUT}"
    }

    /**
     * 检查缓存是否过期
     */
    private fun isExpired(timestamp: Long): Boolean {
        return System.currentTimeMillis() - timestamp > CACHE_TIMEOUT
    }

    /**
     * 清空缓存
     */
    fun clear() {
        cache.evictAll()
        Log.d(TAG, "清空特征缓存")
    }

    /**
     * 缓存的特征数据
     */
    private data class CachedFeature(
        val features: FloatArray,
        val timestamp: Long
    ) {
        override fun equals(other: Any?): Boolean {
            if (this === other) return true
            if (javaClass != other?.javaClass) return false

            other as CachedFeature

            if (!features.contentEquals(other.features)) return false
            if (timestamp != other.timestamp) return false

            return true
        }

        override fun hashCode(): Int {
            var result = features.contentHashCode()
            result = 31 * result + timestamp.hashCode()
            return result
        }
    }
} 